import React, { Component } from 'react';
import { Row, Col, Form, Table, Input, InputNumber, Button, Popconfirm, Upload, Icon, Cascader, message, Popover, Checkbox, Select, Modal } from 'antd';

import styles from './AutomaticProducts.less';

const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;


class AutomaticTable extends Component {
  constructor() {
    super();
    this.state = {
      skuData: [],
      previewVisible: false,
      previewImage: '',
      batchFileList: [],
    };
  }

  componentWillReceiveProps(...args) {
    if (args[0].data instanceof Array && args[0].data.length > 0 && this.state.skuData.length === 0) {
      this.initData(args[0].data);
    }
  }
  
  getValue(callback) {
    const { form } = this.props;
    const AutomaticOrderDetailList = [];
    form.validateFieldsAndScroll((err, fieldsSku) => {
      if (err) return;
      let count = 1;
      const keys = Object.keys(fieldsSku);
			while (Object.prototype.hasOwnProperty.call(fieldsSku, `r_${count}_quantity`)) {
		    const skuSingle = {};
		    keys.forEach((key) => {
		      if (key.match(`r_${count}_`) && fieldsSku[key]) {
		        skuSingle[key.split(`r_${count}_`)[1]] = fieldsSku[key];
		      }
		    });
		    // 处理图片
		    if (skuSingle.orderPic) {
		      const uploadMainPic = [];
		      skuSingle.orderPic.forEach((el, index) => {
		        uploadMainPic.push({
		          type: el.type,
		          uid: `i_${index}`,
		          url: el.url || el.response.data,
		        });
		      });
		      skuSingle.orderPic = JSON.stringify({ picList: uploadMainPic });
		    }
		    AutomaticOrderDetailList.push(skuSingle);
		    count += 1;
			}
      if (AutomaticOrderDetailList.length < 1) {
        message.error('请至少填写一项订单信息');
        return;
      }
      if (callback) callback(AutomaticOrderDetailList);
    });
  }
  clearValue() {
    const { form } = this.props;
    this.setState({ skuData: [], sortedInfo: null}, () => {
      form.resetFields();
    });
  }
  initData(data) {
    data.forEach((el, index) => {
      el.key = index + 1;
    });
    this.setState({ skuData: data });
  }
  addItem() {
    const { skuData } = this.state;
    const skuLen = skuData.length;
    const lastId = skuLen < 1 ? 0 : skuData[skuData.length - 1].key;
    const newId = parseInt(lastId, 10) + 1;

    const newItem = {
      // id: newId,
      key: newId,
      autoDetialNo: '',
      itemUrl: '',
      quantity: '',
      orderPic: '',
      detailTitle: '',
    };
    skuData.push(newItem);
    this.setState({ skuData });
  }

  delItem(key) {
    const { skuData } = this.state;
    const newSkuData = skuData.filter(item => key !== item.key);
    this.setState({ skuData: newSkuData }, () => {
      setTimeout(() => {
        this.setState({ skuData: newSkuData.map((el, index) => { el.key = index + 1; return el; }) });
      }, 100);
    });
  }
  checkImg(rules, values, callback) {
    callback();
  }

  handleCancel() {
    this.setState({ previewVisible: false });
  }

  render() {
    const p = this;
    const { form, parent, packageScales, scaleTypes } = this.props;
    const { getFieldDecorator } = form;
    const { skuData, previewImage, previewVisible } = this.state;
    // 注册props
    if (!parent.clearSkuValue) parent.clearSkuValue = this.clearValue.bind(this);
    if (!parent.getSkuValue) parent.getSkuValue = this.getValue.bind(this);
    const uploadProps = {
      action: '/haierp1/uploadFile/picUpload',
      listType: 'picture-card',
      data(file) {
        return {
          pic: file.name,
        };
      },
      beforeUpload(file) {
        const isImg = file.type === 'image/jpeg' || file.type === 'image/bmp' || file.type === 'image/gif' || file.type === 'image/png';
        if (!isImg) { message.error('请上传图片文件'); }
        return isImg;
      },
      name: 'pic',
      onPreview(file) {
        p.setState({
          previewImage: file.url || file.thumbUrl,
          previewVisible: true,
        });
      },
      onChange(info) {
        if (info.file.status === 'done') {
          if (info.file.response && info.file.response.success) {
            message.success(`${info.file.name} 成功上传`);
            // 添加文件预览
            const newFile = info.file;
            info.fileList = info.fileList.slice(-1);
            newFile.url = info.file.response.data;
          } else { message.error(`${info.file.name} 解析失败：${info.file.response.msg || info.file.response.errorMsg}`); }
        } else if (info.file.status === 'error') { message.error(`${info.file.name} 上传失败`); }
      },
    };
    const modalTableProps = {
      columns: [
        {
          title: '详情单号',
          dataIndex: 'autoDetialNo',
          key: 'autoDetialNo',
          width: '12%',
          render(t, r) {
            return (
              <FormItem>
              	{getFieldDecorator(`r_${r.key}_id`, { initialValue: r.id || null })(
                  <Input style={{ display: 'none' }} />)}
                {getFieldDecorator(`r_${r.key}_autoDetialNo`, { initialValue: t || '' })(
                  r.autoDetialNo ? <Input placeholder="请填写SKU代码" disabled /> : <span style={{ color: '#ccc' }}>自动生成</span>,
                )}
              </FormItem>
            );
          },
        },
        {
          title: '商品链接',
          dataIndex: 'itemUrl',
          key: 'itemUrl',
          width: '15%',
          render(t, r) {
            return (
              <FormItem>
                {getFieldDecorator(`r_${r.key}_itemUrl`, {
                	initialValue: t || '' ,
                	rules: [{ required: true, message: '请填写链接' }],
                })(
                  <Input placeholder="请填写链接" />)}
              </FormItem>
            );
          },
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          key: 'quantity',
          width: '10%',
          render(t, r) {
            return (
              <FormItem>
                {getFieldDecorator(`r_${r.key}_quantity`, { 
                	initialValue: t || '', 
                	rules: [{ required: true, message: '请填写数量' }],
                })(
                  <Input placeholder="请填写数量" />)}
              </FormItem>
            );
          },
        },
        {
          title: '商品图片',
          dataIndex: 'orderPic',
          key: 'orderPic',
          width: '10%',
          render(t, r) {
            const picList = t ? JSON.parse(t).picList || [] : [];
            const formValue = form.getFieldValue(`r_${r.key}_orderPic`);
            let showAdd = false;
            if (formValue && formValue.length < 1) showAdd = true;
            if (picList.length < 1 && !formValue) showAdd = true;
            return (
              <FormItem>
                {getFieldDecorator(`r_${r.key}_orderPic`, {
                  initialValue: t ? picList : formValue,
                  valuePropName: 'fileList',
                  getValueFromEvent(e) {
                    if (!e || !e.fileList) {
                      return e;
                    }
                    const { fileList } = e;
                    return fileList;
                  },
                  rules: [{ validator: p.checkImg.bind(p) }],
                })(
                  <Upload {...uploadProps} className={styles.picStyle}>
                    {showAdd && <Icon type="plus" style={{ fontSize: 10 }} />}
                  </Upload>,
                )}
              </FormItem>
            );
          },
        },
        {
          title: '备注',
          dataIndex: 'detailTitle',
          key: 'detailTitle',
          width: '15%',
          render(t, r) {
            return (
              <FormItem>
                {getFieldDecorator(`r_${r.key}_detailTitle`, { initialValue: t || '' })(
                  <Input placeholder="请填写" />)}
              </FormItem>
            );
          },
        },
        {
          title: '操作',
          key: 'operator',
          width: '15%',
          render(text, record) {
            return (
              <Popconfirm title="确定删除?" onConfirm={p.delItem.bind(p, record.key)}>
                <a href="javascript:void(0)">删除</a>
              </Popconfirm>
            );
          },
        },
      ],
      dataSource: skuData,
      bordered: false,
    };
    return (
    	<div>
	      <Row>
	        <Col className={styles.productModalBtn}>
	          <Button type="primary" size="large" style={{ float: 'right',marginBottom:10}} onClick={this.addItem.bind(this)}>新增订单</Button>
	        </Col>
        </Row>
        <Table
          {...modalTableProps}
          rowKey={record => record.key}
          pagination={false}
          scroll={{ x: '100%'}}
        />
        <Modal visible={previewVisible} title="预览图片" footer={null} onCancel={this.handleCancel.bind(this)} style={{ marginLeft: '40%' }} >
          <img role="presentation" src={previewImage} style={{ width: '100%' }} />
        </Modal>
      </div>
    );
  }
}

export default Form.create()(AutomaticTable);
